package com.mars.weixin.web.weixin.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.mars.base.common.utils.date.DateUtils;
import com.mars.base.common.utils.security.SecurityUtils;
import com.mars.base.web.BaseController;
import com.mars.weixin.common.WeixinConstant;
import com.mars.weixin.web.handler.WeixinRequestHandler;

/**
 * 微信公众号入口
 * @author yhaoquan
 *
 */
@RestController
@RequestMapping(value="/weixin")
public class WeixinController extends BaseController {

	private static final String TOKEN = WeixinConstant.TOKEN;

	/**
	 * 微信接入
	 * @param request
	 * @param response
	 */
	@RequestMapping(method=RequestMethod.GET)
	public void connect(HttpServletRequest request, HttpServletResponse response) {
		try {
			logger.debug("请求的URL: "+ request.getRequestURL().toString());  
	        
			//接收微信发送过来的参数
			String signature = request.getParameter("signature");	// 微信加密签名  
			String timestamp = request.getParameter("timestamp");	// 时间戳  
			String nonce = request.getParameter("nonce");			// 随机数  
			String echostr = request.getParameter("echostr");		// 随机字符串  
			
			logger.debug("微信令牌：{}", TOKEN);
			logger.debug("微信加密签名：{}", signature);
			logger.debug("时间戳：{}", timestamp);
			logger.debug("随机数：{}", nonce);
			logger.debug("随机字符串：{}", echostr);
			
			if(null == TOKEN || null == timestamp || null == nonce) {
				logger.error("非微信服务器访问，无法正常接入微信。");
			} else {
				//1. 将token、timestamp、nonce三个参数进行字典序排序  
				String[] str = { TOKEN, timestamp, nonce };  
				Arrays.sort(str); 
				
				//2. 将三个参数字符串拼接成一个字符串进行sha1加密  
				String digest = SecurityUtils.sha1(str[0] + str[1] + str[2]);  
				
				//3. 确认请求来至微信  
				if (digest.equals(signature)) {  
					//完成相互认证
					response.getWriter().write(echostr);  
					logger.info("微信服务器接入生效，时间[{}]", DateUtils.getDateTime());
				} else {
					logger.info("微信服务器接入失败，时间[{}]", DateUtils.getDateTime());  
				}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}  
	}
	
	/**
	 * 接收消息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(method=RequestMethod.POST)
	public void wexinMessageHandler(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8"); 
        
        // 调用核心业务类接收消息、处理消息  
        String respMessage = WeixinRequestHandler.processRequest(request);  
        
        // 响应消息  
        PrintWriter out = response.getWriter();  
        out.print(respMessage);
        out.close(); 
	}

}
